﻿@page "/UserManger"
<Table TItem="User"
       IsPagination="true" PageItemsSource="new int[]{20,10,30}"
       IsStriped="true" IsBordered="true" IsMultipleSelect="true"
       IsExtendButtonsInRowHeader="false" AutoGenerateColumns="true"
       ShowToolbar="true" ShowExtendButtons="true" ShowSkeleton="true"
       OnQueryAsync="@OnQueryAsync"
       OnAddAsync="@OnAddAsync"
       OnSaveAsync="@OnSaveAsync"
       OnDeleteAsync="@OnDeleteAsync">
    <TableColumns>
        <TableColumn @bind-Field="@context.SysName"  />
        <TableColumn @bind-Field="@context.RealName"  />
    </TableColumns>
    <BeforeRowButtonTemplate Context="value">
        <TableCellButton OnClick="()=>{OnClick(value.Id);}">权限管理</TableCellButton>
    </BeforeRowButtonTemplate>
</Table>

@code {
    [Inject]
    [NotNull]
    public ISqlSugarClient? db { get; set; }
    [Inject]
    [NotNull]
    private DialogService? DialogService { get; set; }
    protected override Task OnInitializedAsync()
    {

        return base.OnInitializedAsync();
    }
    public void OnClick(long id)
    {
        DialogService.ShowModal<UpdateRole>(new ResultDialogOption()
            {
                ComponentParameters = new Dictionary<string, object>
                {
                    [nameof(UpdateRole.Id)] = id,
                }
            });
    }
    private Task<User> OnAddAsync()
    {
        return Task.FromResult(new User() { });
    }

    private async Task<QueryData<User>> OnQueryAsync(QueryPageOptions options)
    {
        var item = await db.Queryable<User>().ToListAsync();
        return new QueryData<User>()
            {
                Items = item,
                TotalCount = item.Count,
            };
    }
    private async Task<bool> OnDeleteAsync(IEnumerable<User> items)
    {
        var res = await db.Deleteable<User>(items).ExecuteCommandAsync();
        return res > 0 ? true : false;
    }
    private async Task<bool> OnSaveAsync(User item, ItemChangedType changedType)
    {
        if (changedType == ItemChangedType.Add)
        {
            await db.Insertable(item).ExecuteReturnSnowflakeIdAsync();
        }
        else
        {
            await db.Updateable(item).ExecuteCommandAsync();
        }
        return true;
    }
}
